'use strict';
const Sequelize = require('sequelize');

const DbProvider = require('../db/db_provider');

const COLUMN_STORE_LIST = Symbol('ColumnStore#list');
const COLUMN_ALL = Symbol('ColumnStore#ALL');

/**
 * bstree
 * [{id,name}]
 */
class ColumnStore {
  constructor() {
    this.db = DbProvider.getNewDb();
  }

  async fetch() {
    if (!this[COLUMN_STORE_LIST]) {
      this[COLUMN_STORE_LIST] = await this[COLUMN_ALL]();
    }
    return this[COLUMN_STORE_LIST] || [];
  }

  list() {
    return this.fetch();
  }

  async getByNameAndLevelCode(name, levelCode) {
    const list = await this.list();
    return list.filter(m => m.name === name && m.levelCode === levelCode);
  }

  /**
 * 查询所有的rcms_Categories
 * @return {Promise<Array>} 数据行
 */
  [COLUMN_ALL]() {
    return this.db.query('select id , code from columns where', {
      raw: true,
      type: Sequelize.QueryTypes.SELECT,
    });
  }
}

module.exports = new ColumnStore();
